﻿using System;

using BodaNetCommunications.Utilities.ComTypes;

namespace BodaNetCommunications.McComs
{
    [AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
    internal class McAddressRange : Attribute
    {
        public McAddressRange(McPLCType mcPLCType, int addressOffset, int minValue, int maxValue)
        {
            McPLCType = mcPLCType;
            MinValue = minValue;
            MaxValue = maxValue;
            AddressOffset = addressOffset;
        }

        public McPLCType McPLCType { get; }
        public int MinValue { get; set; }
        public int MaxValue { get; set; }

        public int AddressOffset { get; set; }


        public string DataAddTransfer(string address)
        {
            try
            {
                var addrInt = int.Parse(address);
                addrInt += AddressOffset;

                if (addrInt > MaxValue || addrInt < MinValue)
                {
                    throw new ArgumentException($"地址[{address}]转换后地址[{addrInt}]超过范围[({MinValue}:{MaxValue})]");
                }

                return addrInt.ToString();
            }
            catch
            {
                return address;
            }
        }
    }
}
